package com.skywolf.chem.utils;



import org.apache.tomcat.util.codec.binary.Base64;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.Key;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Random;

/**
 * 登陆密码  ASE中密码分组链接模式CBC
 * Created by zh on 2018/7/14.
 */
public class CryptUtil {
    private static final String CBC = "/CBC/NoPadding";
    private final static String AES = "AES";

    /**
     * 解密-主要用户用户token的加解密
     * @param cipher
     * @param keyStr
     * @return
     */
    public static String IMDes3Decode(String cipher, String keyStr) {
        String result = null;
        if (null == cipher) {
            return null;
        }
        try {
            cipher = URLDecoder.decode(cipher, "UTF-8");
            byte[] key = keyStr.getBytes("UTF-8");
            byte[] keyReal = new byte[64];
            System.arraycopy(key, 0, keyReal, 0, key.length);

            byte[] data = Base64.decodeBase64(cipher);
            byte[] keyiv = {data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7]};//[60, 115, 80, -119, 123, -73, 94, 34]
            byte[] dataReal = new byte[data.length - 8];
            System.arraycopy(data, 8, dataReal, 0, dataReal.length);

            byte[] str6 = des3DecodeCBC(keyReal, keyiv, dataReal);
            result = new String(str6, "UTF-8").trim();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 加密--主要用户用户token的加解密
     * @param cipher
     * @param keyStr
     * @return
     */
    public static String IMDes3Encode(String cipher, String keyStr) {
        String result = null;
        if (null == cipher) {
            return null;
        }
        try {
            byte[] keyReal = new byte[64];
            byte[] key = keyStr.getBytes("UTF-8");
            System.arraycopy(key, 0, keyReal, 0, key.length);
            byte[] dataReal = cipher.getBytes("UTF-8");
            byte[] dataPadding = new byte[dataReal.length + (8 - dataReal.length % 8)];
            System.arraycopy(dataReal, 0, dataPadding, 0, dataReal.length);
            Random r = new Random();
            byte[] keyiv = new byte[8];
            keyiv[0] = (byte) r.nextInt(256);
            keyiv[1] = (byte) r.nextInt(256);
            keyiv[2] = (byte) r.nextInt(256);
            keyiv[3] = (byte) r.nextInt(256);
            keyiv[4] = (byte) r.nextInt(256);
            keyiv[5] = (byte) r.nextInt(256);
            keyiv[6] = (byte) r.nextInt(256);
            keyiv[7] = (byte) r.nextInt(256);

            byte[] encodeData = des3EncodeCBC(keyReal, keyiv, dataPadding);

            byte[] dataWithIv = new byte[encodeData.length + 8];
            System.arraycopy(keyiv, 0, dataWithIv, 0, keyiv.length);
            System.arraycopy(encodeData, 0, dataWithIv, 8, encodeData.length);

            String dataBase64 = Base64.encodeBase64String(dataWithIv);
            result = URLEncoder.encode(dataBase64, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * CBC加密
     * @param key   密钥
     * @param keyiv IV
     * @param data  明文
     * @return Base64编码的密文
     * @throws Exception
     */
    public static byte[] des3EncodeCBC(byte[] key, byte[] keyiv, byte[] data) throws Exception {
        Key deskey = null;
        DESedeKeySpec spec = new DESedeKeySpec(key);
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
        deskey = keyfactory.generateSecret(spec);
        Cipher cipher = Cipher.getInstance("desede" + CBC);
        IvParameterSpec ips = new IvParameterSpec(keyiv);
        cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
        byte[] bOut = cipher.doFinal(data);
        return bOut;
    }

    /**
     * CBC解密
     * @param key   密钥
     * @param keyiv IV
     * @param data  Base64编码的密文
     * @return 明文
     * @throws Exception
     */
    public static byte[] des3DecodeCBC(byte[] key, byte[] keyiv, byte[] data) throws Exception {
        DESedeKeySpec spec = new DESedeKeySpec(key);
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
        Key deskey = keyfactory.generateSecret(spec);
        Cipher cipher = Cipher.getInstance("desede" + CBC);
        IvParameterSpec ips = new IvParameterSpec(keyiv);
        cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
        byte[] bOut = cipher.doFinal(data);
        return bOut;
    }

    public static void encodeFile(String filePath, String key) throws Exception {
        File file = new File(filePath);
        if (file.isFile()) {
            BufferedReader br = new BufferedReader(new FileReader(file));
            String data = null;
            BufferedWriter bw = new BufferedWriter(new FileWriter(filePath + ".encode"));
            while ((data = br.readLine()) != null) {
                bw.write(IMDes3Encode(data, key));
                bw.write('\r');
                bw.write('\n');
            }
            bw.close();
            br.close();
        }
    }

    public static void main(String[] args) {
//        System.out.println(IMDes3Encode("test|12345612312", "EDAD1123AS"));
//
//        System.out.println(IMDes3Decode("Yv3UFliqq%2BTHmbcAbEvVtUoDOd%2B%2FYMGW", "EDAD1123AS"));

        String jiami = encryptAES128("wenlong123","EDAD1123AS");
        System.out.println("加密后的内容：" +jiami);

        String jiemi = decryptAES128("D13B169782D97DD0C84E0B56EA518A91","EDAD1123AS");
        System.out.println("解密后的内容：" +jiemi);
    }



    /**
     * AES加密字符串
     * @param content  需要被加密的字符串
     * @param keyStr   加密需要的密码
     * @return 密文
     */
    public static String encryptAES128(String content, String keyStr) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance(AES); //KeyGenerator提供（对称）密钥生成器的功能。使用getInstance 类方法构造密钥生成器。
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(keyStr.getBytes());
            kgen.init(128, secureRandom);//使用用户提供的随机源初始化此密钥生成器，使其具有确定的密钥大小。
            byte[] enCodeFormat = kgen.generateKey().getEncoded();
            SecretKeySpec secretKey = new SecretKeySpec(enCodeFormat, AES);//使用SecretKeySpec类来根据一个字节数组构造一个 SecretKey,，而无须通过一个（基于 provider 的）SecretKeyFactory.
            Cipher cipher = Cipher.getInstance(AES);// 创建密码器   //为创建 Cipher 对象，应用程序调用 Cipher 的 getInstance 方法并将所请求转换 的名称传递给它。还可以指定提供者的名称（可选）。
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);// 初始化
            byte[] result = cipher.doFinal(content.getBytes()); //按单部分操作加密或解密数据，或者结束一个多部分操作。数据将被加密或解密（具体取决于此 Cipher 的初始化方式）。
            return parseByte2HexStr(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密AES加密过的字符串
     * @param content  AES加密过过的内容
     * @param keyStr 加密时的密码
     * @return 明文
     */
    public static String decryptAES128(String content, String keyStr) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance(AES);
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(keyStr.getBytes());
            kgen.init(128, secureRandom);
            byte[] enCodeFormat = kgen.generateKey().getEncoded();
            SecretKeySpec secretKey = new SecretKeySpec(enCodeFormat, AES);
            Cipher cipher = Cipher.getInstance(AES);// 创建密码器
            //Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"算法/模式/补码方式"
            cipher.init(Cipher.DECRYPT_MODE, secretKey);// 初始化
            byte[] result = cipher.doFinal(parseHexStr2Byte(content));
            return new String(result); // 明文
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**将二进制转换成16进制
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**将16进制转换为二进制
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length()/2];
        for (int i = 0;i< hexStr.length()/2; i++) {
            int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
            int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /**
     * 功能：MD5加密
     * @param str 加密的源字符串
     * @return 加密串 长度32位(hex串)
     */
    public static String EncoderByMd5(String str) {
        try{
            MessageDigest md5=MessageDigest.getInstance("MD5");
            BASE64Encoder base64en = new BASE64Encoder();
            //加密后的字符串
            String newstr=base64en.encode(md5.digest(str.getBytes("utf-8")));
            return newstr;
        }catch (Exception e){
            return null;
        }
    }


    /**
     * 用户密码加盐混淆
     * @param pwd
     * @param uid
     * @return
     */
    public static String PwdUtils(String pwd,String uid){
        //取值用户uid的前五位加盐混淆
        String pwdUid = uid.substring(0,5);
        return  CryptUtil.EncoderByMd5(CryptUtil.EncoderByMd5(pwd)+pwdUid);
    }

}
